package com.qihoo.finance.fake.variety.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.ParameterizedTypeImpl;
import com.qihoo.finance.fake.service.FakeSourceService;
import com.qihoo.finance.fake.variety.VarietyEnum;
import com.qihoo.finance.fake.variety.VarietyService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

@Service
public class FixedVarietyBaseDbIpServiceImpl implements VarietyService {
    Logger logger = LogManager.getLogger(FixedVarietyBaseDbIpServiceImpl.class);

    private FakeSourceService fakeSourceService;

    public FixedVarietyBaseDbIpServiceImpl(FakeSourceService fakeSourceService) {
        this.fakeSourceService = fakeSourceService;
    }

    @Override
    public Object populate(String interfaceName, Method method, String mockValue) throws Exception {
        Type[] returnTypes;
        Type returnType = method.getGenericReturnType();
        if(returnType instanceof ParameterizedType){
            returnTypes = ((sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl)returnType).getActualTypeArguments();
        }else {
            returnTypes = new Type[]{returnType};
        }

        String str = fakeSourceService.queryFakeDbIpResult(interfaceName, method.getName(), RpcContext.getContext().getRemoteHost());
        logger.info("fixed_db_ip获取配置ip: {}, value: {}", RpcContext.getContext().getRemoteHost(), str);
        str = StringUtils.defaultString(str, mockValue);
        if (StringUtils.isNotBlank(str)) {
            ParameterizedTypeImpl parameterizedType = null;
            Type[] fastJsonReturnTypes = new Type[returnTypes.length + 1];
            System.arraycopy(returnTypes, 0, fastJsonReturnTypes, 1, returnTypes.length);
            fastJsonReturnTypes[0] = method.getReturnType();

            //支持多级泛型的解析
            for (int i = fastJsonReturnTypes.length - 1; i > 0; i--) {
                parameterizedType = new ParameterizedTypeImpl(new Type[]{parameterizedType == null ? fastJsonReturnTypes[i] : parameterizedType}, null, fastJsonReturnTypes[i - 1]);
            }
            return JSON.parseObject(str, parameterizedType);
        } else {
            if (returnTypes.length > 0 && "com.qihoo.finance.msf.api.domain.Response".equals(returnTypes[0].getTypeName())) {
                return new com.qihoo.finance.msf.api.domain.Response().fail("", String.format("%s%s%s%s%s", "未加载到", interfaceName, "#", method.getName(), "对应的fake配置"));
            }
            logger.info("{}#{}固定值mock配置结果为空", interfaceName, method.getName());
        }
        return null;
    }

    @Override
    public VarietyEnum getVarietyType() {
        return VarietyEnum.FIXED_DB_IP;
    }
}
